package cn.yeziji.forum.dao.impl;

import cn.yeziji.forum.common.enums.status.PayStatus;
import cn.yeziji.forum.converter.PayConverter;
import cn.yeziji.forum.dao.base.MerchantWechatPayInfoBaseDao;
import cn.yeziji.forum.dao.intf.MerchantWechatPayInfoDao;
import cn.yeziji.forum.dto.pay.merchant.MerchantWechatPayInfoDTO;
import cn.yeziji.forum.entity.MerchantWechatPayInfoEntity;
import cn.yeziji.forum.exception.PayException;
import cn.yeziji.forum.mapper.MerchantWechatPayInfoMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Optional;

/** 商户微信支付信息 服务接口实现类 */
@Repository
public class MerchantWechatPayInfoDaoImpl extends MerchantWechatPayInfoBaseDao
    implements MerchantWechatPayInfoDao {

  @Resource
  private MerchantWechatPayInfoMapper merchantWechatPayInfoMapper;

  @Override
  public int save(MerchantWechatPayInfoDTO infoDTO) {
    if (infoDTO == null) {
      return 0;
    }
    MerchantWechatPayInfoEntity entity =
        PayConverter.INSTANCE.merchantWechatPayInfoDTOConvertToEntity(infoDTO);
    if (infoDTO.hasUpdateId()) {
      this.updateById(entity);
    } else {
      this.save(entity);
    }
    return entity.getId();
  }

  @Override
  public MerchantWechatPayInfoDTO getByUserId(Integer userId) {
    Optional<MerchantWechatPayInfoEntity> one = this.findOne(this.query().where.userId().eq(userId).end());
    if (one.isPresent()) {
      return PayConverter.INSTANCE.merchantWechatPayInfoEntityConvertToDTO(one.get());
    }
    throw new PayException(PayStatus.USER_NO_SUPPORT_WECHAT_PAY);
  }
}
